package com.zw.admin.server.utils;

import com.alibaba.fastjson.JSONObject;
import com.zw.admin.server.dao.DeviceDao;
import com.zw.admin.server.dao.GuardDao;
import com.zw.admin.server.dto.GuardDto;
import com.zw.admin.server.model.Device;
import com.zw.admin.server.model.Guard;
import com.zw.admin.server.model.ResponseBean;
import com.zw.admin.server.service.DeviceService;
import com.zw.admin.server.service.GuardService;
import com.zw.admin.server.service.impl.DeviceServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.text.*;

/*
 * 获取当前的ISO8601标准时间
 * 将yyyy-MM-dd转成ISO8601时间
 * */
@Component
public class Timetrans {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceDao deviceDao;//NEW
    @Autowired
    private GuardDao guardDao;
    @Autowired
    private GuardService guardService;

    static String daka_time = "09";

    public String now_time() {
        // 将当下时间变成标准时间
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssX:'00'");  //海康用的那种日期格式
        df.setTimeZone(tz);
        String nowAsISO = df.format(new Date());
        return nowAsISO;
    }

    public String timetran(String input_time) {
        // 将前端传的时间变成标准时间
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        input_time = input_time + "-" + daka_time;
        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssX:'00'");
        df.setTimeZone(tz);

        SimpleDateFormat deal_input = new SimpleDateFormat("YYYY-MM-dd-HH");
        try {
            Date date = deal_input.parse(input_time);
            String nowAsISO = df.format(date);
            return nowAsISO;
        } catch (ParseException px) {
            px.printStackTrace();
            return "Error";
        }
    }

    public Timestamp timetran2Ts(String input_time) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+08:00");
        Date date = dateFormat.parse(input_time);
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return new Timestamp(date.getTime());
    }

    public void updateAllGuardInfo() throws ParseException {
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssX:'00'");  //海康用的那种日期格式
        df.setTimeZone(tz);
        Date nowdate = new Date();
        String nowAsISO = df.format(nowdate);  //现在的标准时间
        String nowAsISO_5 = df.format(nowdate.getTime() - (24 * 60 * 60000));  // 前一天的标准时间
//        String search_json = new Inter_test().Person_Eve_By_Door(1, 100, nowAsISO_5, nowAsISO);

        List<Guard> guards = guardDao.selectAll();
        //清空表中原有数据
        for (Guard guard : guards) {
            guardDao.delete(guard);
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeIndex = formatter.format(new Date());

        //插入最新数据
        while (true) {
            if (formatter.parse(timeIndex).before(formatter.parse("2020-09-27 00:00:00"))) {
                break;
            }

            System.out.println(timeIndex);
            String startTime = df.format(formatter.parse(timeIndex).getTime() - (24 * 60 * 60000));
            String endTime = df.format(formatter.parse(timeIndex).getTime());
            String search_json = new Inter_test().Person_Eve_By_Door(1, 1000, startTime, endTime);

            String data = JSONObject.parseObject(search_json).get("data").toString();
            String listData = JSONObject.parseObject(data).get("list").toString();
            List<GuardDto> guardList = JSONObject.parseArray(listData, GuardDto.class);

            DateFormat formatDelayTime = new SimpleDateFormat("HH:mm");
            String delayTime = guardService.getDelayTime();
            String earlyExitTime = guardService.getEarlyExitTime();

            for (GuardDto guard : guardList) {

                DateFormat sdf = new SimpleDateFormat("HH:mm");
                String checkinTime = sdf.format(timetran2Ts(guard.getEventTime()));

                Guard guardEntity = new Guard();
                BeanUtils.copyProperties(guard, guardEntity);
                guardEntity.setEventTime(timetran2Ts(guard.getEventTime()));
                //如果打卡时间晚于迟到时间，则判定为迟到
                if (formatDelayTime.parse(checkinTime).after(formatDelayTime.parse(delayTime)) && guard.getDevName().equals("签到打卡")) {
                    //1代表迟到
                    guardEntity.setIsDelay(1);
                }

                //如果签退打卡时间早于下班时间，则判定为早退
                if (formatDelayTime.parse(checkinTime).before(formatDelayTime.parse(earlyExitTime)) && guard.getDevName().equals("签退打卡")) {
                    //1代表迟到
                    guardEntity.setIsEarlyExit(1);
                }
                guardDao.insert(guardEntity);
            }

            timeIndex = formatter.format(formatter.parse(timeIndex).getTime() - (24 * 60 * 60000));
        }


    }

    public void saveevent() throws ParseException {

        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssX:'00'");  //海康用的那种日期格式
        df.setTimeZone(tz);
        Date nowdate = new Date();
        String nowAsISO = df.format(nowdate);  //现在的标准时间
        String nowAsISO_5 = df.format(nowdate.getTime() - 5 * 60000);  // 5分钟后的标准时间
        String search_json = new Inter_test().Person_Eve_By_Door(1, 100, nowAsISO_5, nowAsISO);

//        String search_json = "{\"code\":\"0\",\"msg\":\"success\",\"data\":{\"pageSize\":10,\"list\":[" +
//                "{\"eventId\":\"f947ad89-a2fc-4a27-bf1b-60e61fca5e40\",\"eventName\":\"acs.acs.eventType.successFace\",\"eventTime\":\"2020-09-05T18:05:29+08:00\",\"personId\":\"46cec86c7041468298716fe4f2708dac\",\"cardNo\":null,\"personName\":\"郭云峰\",\"orgIndexCode\":\"d0f61243-6bbd-467b-a616-31f924ac54cd\",\"orgName\":\"哈尔滨办公室/资讯部\",\"doorName\":\"签到打卡_门_1\",\"doorIndexCode\":\"c64f3bb992dd420e9a0acf7066c606be\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"no-pcnvr\",\"svrIndexCode\":\"\",\"eventType\":196893,\"inAndOutType\":1,\"readerDevIndexCode\":\"ea43d9b57bb94ecbb9428d73ddb2494f\",\"readerDevName\":\"读卡器_1\",\"devIndexCode\":\"e3cf818926ab4c39be985af4c6e9c5a2\",\"devName\":\"签到打卡\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T18:05:23.135+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":\"2\"}," +
//                "{\"eventId\":\"6b1be8df-5e36-43c2-8b2d-c38042423e53\",\"eventName\":\"acs.acs.eventType.successFace\",\"eventTime\":\"2020-09-05T18:05:22+08:00\",\"personId\":\"46cec86c7041468298716fe4f2708dac\",\"cardNo\":null,\"personName\":\"郭云峰\",\"orgIndexCode\":\"d0f61243-6bbd-467b-a616-31f924ac54cd\",\"orgName\":\"哈尔滨办公室/资讯部\",\"doorName\":\"签退打卡_门_1\",\"doorIndexCode\":\"e8fddf4827134d3da08f827d51a1b434\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"no-pcnvr\",\"svrIndexCode\":\"\",\"eventType\":196893,\"inAndOutType\":1,\"readerDevIndexCode\":\"9b6268a943eb44b9bed30edb5a28ed84\",\"readerDevName\":\"读卡器_1\",\"devIndexCode\":\"b0f66c8c82234b14bcefbac02a7b45c7\",\"devName\":\"签退打卡\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T18:04:38.290+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":\"2\"}," +
//                "{\"eventId\":\"c406a0f9-426d-4ac3-9033-dcbd7b905915\",\"eventName\":\"acs.acs.eventType.failForFace\",\"eventTime\":\"2020-09-15T17:45:30+08:00\",\"personId\":null,\"cardNo\":null,\"personName\":null,\"orgIndexCode\":null,\"orgName\":null,\"doorName\":\"签退打卡_门_1\",\"doorIndexCode\":\"e8fddf4827134d3da08f827d51a1b434\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"no-pcnvr\",\"svrIndexCode\":\"\",\"eventType\":197151,\"inAndOutType\":1,\"readerDevIndexCode\":\"9b6268a943eb44b9bed30edb5a28ed84\",\"readerDevName\":\"读卡器_1\",\"devIndexCode\":\"b0f66c8c82234b14bcefbac02a7b45c7\",\"devName\":\"签退打卡\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T17:44:47.149+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":null}," +
//                "{\"eventId\":\"82a859dd-65b9-4b69-afb4-2bb32f6838ea\",\"eventName\":\"acs.acs.eventType.failForFace\",\"eventTime\":\"2020-09-15T17:45:26+08:00\",\"personId\":null,\"cardNo\":null,\"personName\":null,\"orgIndexCode\":null,\"orgName\":null,\"doorName\":\"签退打卡_门_1\",\"doorIndexCode\":\"e8fddf4827134d3da08f827d51a1b434\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"no-pcnvr\",\"svrIndexCode\":\"\",\"eventType\":197151,\"inAndOutType\":1,\"readerDevIndexCode\":\"9b6268a943eb44b9bed30edb5a28ed84\",\"readerDevName\":\"读卡器_1\",\"devIndexCode\":\"b0f66c8c82234b14bcefbac02a7b45c7\",\"devName\":\"签退打卡\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T17:44:43.128+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":null}," +
//                "{\"eventId\":\"8c3cbae6-1fff-486d-974d-08176ce33afe\",\"eventName\":\"acs.acs.eventType.failForFace\",\"eventTime\":\"2020-09-15T17:45:22+08:00\",\"personId\":null,\"cardNo\":null,\"personName\":null,\"orgIndexCode\":null,\"orgName\":null,\"doorName\":\"签退打卡_门_1\",\"doorIndexCode\":\"e8fddf4827134d3da08f827d51a1b434\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"no-pcnvr\",\"svrIndexCode\":\"\",\"eventType\":197151,\"inAndOutType\":1,\"readerDevIndexCode\":\"9b6268a943eb44b9bed30edb5a28ed84\",\"readerDevName\":\"读卡器_1\",\"devIndexCode\":\"b0f66c8c82234b14bcefbac02a7b45c7\",\"devName\":\"签退打卡\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T17:44:39.103+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":null}," +
//                "{\"eventId\":\"a6eedea2-4703-4507-95ef-a8138a7ca006\",\"eventName\":\"acs.acs.eventType.failForFace\",\"eventTime\":\"2020-09-15T17:45:13+08:00\",\"personId\":null,\"cardNo\":null,\"personName\":null,\"orgIndexCode\":null,\"orgName\":null,\"doorName\":\"签退打卡_门_1\",\"doorIndexCode\":\"e8fddf4827134d3da08f827d51a1b434\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"no-pcnvr\",\"svrIndexCode\":\"\",\"eventType\":197151,\"inAndOutType\":1,\"readerDevIndexCode\":\"9b6268a943eb44b9bed30edb5a28ed84\",\"readerDevName\":\"读卡器_1\",\"devIndexCode\":\"b0f66c8c82234b14bcefbac02a7b45c7\",\"devName\":\"签退打卡\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T17:44:29.079+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":null}," +
//                "{\"eventId\":\"af375155-6088-439c-963c-55cef126bae4\",\"eventName\":\"acs.acs.eventType.infoOpenDoorByButton\",\"eventTime\":\"2020-09-15T17:31:23+08:00\",\"personId\":null,\"cardNo\":null,\"personName\":null,\"orgIndexCode\":null,\"orgName\":null,\"doorName\":\"签退打卡_门_1\",\"doorIndexCode\":\"e8fddf4827134d3da08f827d51a1b434\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"\",\"svrIndexCode\":\"\",\"eventType\":198916,\"inAndOutType\":-1,\"readerDevIndexCode\":null,\"readerDevName\":null,\"devIndexCode\":\"b0f66c8c82234b14bcefbac02a7b45c7\",\"devName\":\"签退打卡\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T17:30:38.857+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":null}," +
//                "{\"eventId\":\"9e3a5530-b2bc-4669-8aa5-f47fe82ef6b5\",\"eventName\":\"acs.acs.eventType.failForFace\",\"eventTime\":\"2020-09-15T17:05:02+08:00\",\"personId\":null,\"cardNo\":null,\"personName\":null,\"orgIndexCode\":null,\"orgName\":null,\"doorName\":\"左通道_门_1\",\"doorIndexCode\":\"1c88270d63484d859ca7b60aaa42ac04\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"no-pcnvr\",\"svrIndexCode\":\"\",\"eventType\":197151,\"inAndOutType\":1,\"readerDevIndexCode\":\"fca13ad7dce846b2b100053a1c9dc8d4\",\"readerDevName\":\"读卡器_1\",\"devIndexCode\":\"4d2a0ac081b04dd9bb2980279c40004e\",\"devName\":\"左通道\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T17:04:26.889+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":null}," +
//                "{\"eventId\":\"f032d105-a3ed-4b96-959c-8e494f57947a\",\"eventName\":\"acs.acs.eventType.failForFace\",\"eventTime\":\"2020-09-15T17:04:51+08:00\",\"personId\":null,\"cardNo\":null,\"personName\":null,\"orgIndexCode\":null,\"orgName\":null,\"doorName\":\"左通道_门_1\",\"doorIndexCode\":\"1c88270d63484d859ca7b60aaa42ac04\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"no-pcnvr\",\"svrIndexCode\":\"\",\"eventType\":197151,\"inAndOutType\":1,\"readerDevIndexCode\":\"fca13ad7dce846b2b100053a1c9dc8d4\",\"readerDevName\":\"读卡器_1\",\"devIndexCode\":\"4d2a0ac081b04dd9bb2980279c40004e\",\"devName\":\"左通道\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T17:04:15.879+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":null}," +
//                "{\"eventId\":\"b10009e4-d9ac-448c-8e9c-b3a659d74237\",\"eventName\":\"acs.acs.eventType.infoOpenDoorByButton\",\"eventTime\":\"2020-09-15T16:49:50+08:00\",\"personId\":null,\"cardNo\":null,\"personName\":null,\"orgIndexCode\":null,\"orgName\":null,\"doorName\":\"签退打卡_门_1\",\"doorIndexCode\":\"e8fddf4827134d3da08f827d51a1b434\",\"doorRegionIndexCode\":\"root000000\",\"picUri\":\"\",\"svrIndexCode\":\"\",\"eventType\":198916,\"inAndOutType\":-1,\"readerDevIndexCode\":null,\"readerDevName\":null,\"devIndexCode\":\"b0f66c8c82234b14bcefbac02a7b45c7\",\"devName\":\"签退打卡\",\"identityCardUri\":\"\",\"receiveTime\":\"2020-09-15T16:49:05.790+08:00\",\"jobNo\":null,\"studentId\":null,\"certNo\":null}],\"total\":340,\"totalPage\":34,\"pageNo\":1}}\n";
        String data = JSONObject.parseObject(search_json).get("data").toString();
        String listData = JSONObject.parseObject(data).get("list").toString();
        List<GuardDto> guardList = JSONObject.parseArray(listData, GuardDto.class);

        DateFormat formatDelayTime = new SimpleDateFormat("HH:mm");
        String delayTime = guardService.getDelayTime();
        String earlyExitTime = guardService.getEarlyExitTime();

        for (GuardDto guard : guardList) {

            DateFormat sdf = new SimpleDateFormat("HH:mm");
            String checkinTime = sdf.format(timetran2Ts(guard.getEventTime()));

            Guard guardEntity = new Guard();
            BeanUtils.copyProperties(guard, guardEntity);
            guardEntity.setEventTime(timetran2Ts(guard.getEventTime()));
            //如果打卡时间晚于迟到时间，则判定为迟到
            if (formatDelayTime.parse(checkinTime).after(formatDelayTime.parse(delayTime)) && guard.getDevName().equals("签到打卡")) {
                //1代表迟到
                guardEntity.setIsDelay(1);
            }


            //如果签退打卡时间早于下班时间，则判定为早退
            if (formatDelayTime.parse(earlyExitTime).before(formatDelayTime.parse(earlyExitTime)) && guard.getDevName().equals("签退打卡")) {
                //1代表迟到
                guardEntity.setIsEarlyExit(1);
            }
            guardDao.insert(guardEntity);


            String CurrentPersonName = guard.getPersonName();
            System.out.println(CurrentPersonName);
            //日期转变为星期*
            DateFormat sdf2 = new SimpleDateFormat("YYYY-MM-dd");
            String CurrentDataName = sdf2.format(timetran2Ts(guard.getEventTime()));
            System.out.println(CurrentDataName);
            String CurrentPersonWeek = getWeek(CurrentDataName);
            System.out.println(CurrentPersonWeek);


            if ((CurrentPersonWeek.equals("星期六") || CurrentPersonWeek.equals("星期日")) && guard.getDevName().equals("签到打卡")) {
                List<Device> select = deviceDao.selectWorkOvertime(CurrentPersonName);
                for (int i = 0; i < select.size(); i++) {
                    String asd = select.get(i).getName();
                    System.out.println(asd + "要开灯");
                    System.out.println(asd + "的编号" + select.get(i).getIotId());
                    //deviceService.updateDeviceStates(select.getIotId(),"1");
                }

            } else if ((CurrentPersonWeek.equals("星期六") || CurrentPersonWeek.equals("星期日")) && guard.getDevName().equals("签退打卡")) {
                List<Device> select = deviceDao.selectWorkOvertime(CurrentPersonName);
                for (int i = 0; i < select.size(); i++) {
                    String asd = select.get(i).getName();
                    System.out.println(asd + "要关灯");
                    System.out.println(asd + "的编号" + select.get(i).getIotId());
                    //deviceService.updateDeviceStates(select.getIotId(),"0");
                }
            }


        }
    }

    //NEW
    public String getWeek(String date) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(date);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }


}



